<template>
  <div class="product-statistics">
    <!-- 搜索框 -->
    <el-card class="filter-card">
      <el-input
        v-model="productId"
        placeholder="输入商品ID查看具体商品数据"
        clearable
        style="width: 220px"
        @keyup.enter="fetchData"
      >
        <template #append>
          <el-button @click="fetchData">
            <el-icon><Search /></el-icon>
          </el-button>
        </template>
      </el-input>
    </el-card>

    <!-- 数据展示区域 -->
    <el-row :gutter="20" v-loading="loading">
      <!-- 第一行卡片 -->
      <el-col :span="6" v-for="(item, index) in mainCards" :key="index">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>{{ item.title }}</span>
              <el-tooltip placement="top">
                <template #content>{{ item.tooltip }}</template>
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-value">
            <template v-if="item.isCurrency">¥</template>
            {{ formatValue(item.value, item.type) }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 转化率和活跃商品数 -->
    <el-row :gutter="20" class="mt-20" v-if="!productId" v-loading="loading">
      <el-col :span="12" v-for="(item, index) in secondaryCards" :key="index">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>{{ item.title }}</span>
              <el-tooltip placement="top">
                <template #content>{{ item.tooltip }}</template>
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <div class="card-value">
            {{ formatValue(item.value, item.type) }}
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热门商品图表 -->
    <el-card class="mt-20">
      <template #header>
        <div class="card-header">
          <span>热门商品浏览量排行</span>
          <el-tooltip placement="top">
            <template #content>展示商品浏览量前10名</template>
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </div>
      </template>
      <div class="chart-container">
        <v-chart :option="hotProductsOption" autoresize />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Search, QuestionFilled } from '@element-plus/icons-vue'
import { getProductAnalytics, getHotProductsRanking } from '@/api/statistics'

// 基础数据
const productId = ref('')
const loading = ref(false)
const analytics = ref({
  totalProducts: 0,
  totalViews: 0,
  totalSales: 0,
  activeProducts: 0,
  totalRevenue: 0,
  conversionRate: 0,
  viewCount: 0,
  clickCount: 0,
  purchaseCount: 0,
  favoriteCount: 0
})

// 主要卡片数据
const mainCards = computed(() => {
  if (productId.value) {
    return [
      {
        title: '浏览量',
        value: analytics.value.viewCount,
        tooltip: '该商品被查看的次数',
        type: 'number',
        isCurrency: false
      },
      {
        title: '点击量',
        value: analytics.value.clickCount,
        tooltip: '该商品被点击的次数',
        type: 'number',
        isCurrency: false
      },
      {
        title: '购买量',
        value: analytics.value.purchaseCount,
        tooltip: '该商品的购买次数',
        type: 'number',
        isCurrency: false
      },
      {
        title: '收藏量',
        value: analytics.value.favoriteCount,
        tooltip: '该商品被收藏的次数',
        type: 'number',
        isCurrency: false
      }
    ]
  } else {
    return [
      {
        title: '总浏览量',
        value: analytics.value.totalViews || 0,
        tooltip: '所有商品被查看的总次数',
        type: 'number',
        isCurrency: false
      },
      {
        title: '商品总数',
        value: analytics.value.totalProducts || 0,
        tooltip: '平台商品总数',
        type: 'number',
        isCurrency: false
      },
      {
        title: '总销量',
        value: analytics.value.totalSales || 0,
        tooltip: '所有商品的总销售数量',
        type: 'number',
        isCurrency: false
      },
      {
        title: '总收入',
        value: analytics.value.totalRevenue || 0,
        tooltip: '所有商品的总销售收入',
        type: 'currency',
        isCurrency: true
      }
    ]
  }
})

// 次要卡片数据（仅在显示总体数据时显示）
const secondaryCards = computed(() => [
  {
    title: '转化率',
    value: analytics.value.conversionRate || 0,
    tooltip: '浏览到购买的转化比率',
    type: 'percent'
  },
  {
    title: '活跃商品数',
    value: analytics.value.activeProducts || 0,
    tooltip: '当前活跃的商品数量',
    type: 'number'
  }
])

// 热门商品数据
const hotProducts = ref([])

// 热门商品图表配置
const hotProductsOption = computed(() => ({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '10%',
    containLabel: true
  },
  xAxis: {
    type: 'value',
    name: '浏览量'
  },
  yAxis: {
    type: 'category',
    data: hotProducts.value.map(item => item.productName),
    axisLabel: {
      width: 100,
      overflow: 'truncate',
      interval: 0
    }
  },
  series: [
    {
      name: '浏览量',
      type: 'bar',
      data: hotProducts.value.map(item => item.viewCount),
      label: {
        show: true,
        position: 'right'
      }
    }
  ]
}))

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const response = await getProductAnalytics(productId.value || null)
    
    // 直接使用响应数据，因为后端直接返回数据对象
    console.log('API Response:', response)
    
    // 直接将响应数据赋值给 analytics
    analytics.value = {
      ...analytics.value,  // 保留默认值
      ...response  // 使用后端返回的数据覆盖
    }
    
    console.log('Updated analytics:', analytics.value)
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 获取热门商品数据
const fetchHotProducts = async () => {
  try {
    const response = await getHotProductsRanking()
    if (response.code === 200) {
      hotProducts.value = response.data.products
    }
  } catch (error) {
    console.error('获取热门商品数据失败:', error)
    ElMessage.error('获取热门商品数据失败')
  }
}

// 格式化数值
const formatValue = (value, type) => {
  if (value === undefined || value === null) return '0'
  
  switch (type) {
    case 'currency':
      return parseFloat(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    case 'percent':
      return (parseFloat(value) * 100).toFixed(2) + '%'
    case 'number':
    default:
      return parseInt(value).toLocaleString('zh-CN')
  }
}

// 监听商品ID变化
watch(productId, () => {
  fetchData()
})

// 初始化
onMounted(() => {
  fetchData()
  fetchHotProducts()
})
</script>

<style scoped>
.product-statistics {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
  margin-top: 10px;
}

.chart-container {
  height: 400px;
  width: 100%;
}
</style> 